package com.example.wechat.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
		// 启用简单的内存消息代理，处理以 "/topic" 开头的消息
		config.enableSimpleBroker("/topic", "/queue", "/user");

		// 设置应用程序消息前缀，以 "/app" 开头的消息会被路由到 @MessageMapping 注解的方法
		config.setApplicationDestinationPrefixes("/app");

		// 设置用户目标前缀，用于私聊消息
		config.setUserDestinationPrefix("/user");
	}

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		// 注册WebSocket端点，支持SockJS
		registry.addEndpoint("/ws").setAllowedOriginPatterns("*").addInterceptors(new HttpSessionHandshakeInterceptor())
				.withSockJS().setHeartbeatTime(30000) // 心跳间隔30秒
				.setDisconnectDelay(5000); // 断开连接延迟5秒

		// 同时支持原生WebSocket
		registry.addEndpoint("/ws-native").setAllowedOriginPatterns("*")
				.addInterceptors(new HttpSessionHandshakeInterceptor());
	}

}